import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.UIManager;
import javax.swing.UIManager.*;
import java.util.*;
import javax.swing.event.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.File;
public class Elite
{
    public static void main(String[] args)
    {
        Elite elite = new Elite();
        elite.setVisible(true);
    }
    private Elite()
    {
        StartLookAndFeell();
        mainFrame.setTitle("Elite");
        mainFrame.setLayout(new BorderLayout());
        tabbedPane = new JTabbedPane();
        tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        mainFrame.add(tabbedPane, BorderLayout.CENTER);
        mainFrame.setJMenuBar(getMenu());
        mainFrame.setSize(WIDTH,HEIGHT);
        mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        mainFrame.addWindowListener(new
            WindowAdapter()
            {
                public void windowClosing(WindowEvent e)
                {
                    exit();
                }
            }
        );
        mainFrame.add(statusBar,BorderLayout.SOUTH);
    }
    public void setVisible(boolean isVisible)
    {
    	mainFrame.setVisible(isVisible);
    }
    private JMenuBar getMenu()
    {
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu(Resources.getString("file"));
	        JMenuItem newItem = new JMenuItem(Resources.getString("new"));
	        JMenuItem openItem = new JMenuItem(Resources.getString("open"));
	        JMenuItem saveItem = new JMenuItem(Resources.getString("save"));
	        JMenuItem saveAsItem = new JMenuItem(Resources.getString("saveAs"));
	        JMenuItem printItem = new JMenuItem(Resources.getString("print"));
	        JMenuItem exitItem = new JMenuItem(Resources.getString("exit"));
        JMenu checkupMenu = new JMenu(Resources.getString("evaluation"));
        	JMenuItem addDateItem = new JMenuItem(Resources.getString("addDate"));
        	JMenuItem deleteDateItem = new JMenuItem(Resources.getString("deleteDate"));
        	JMenuItem dataCompareItem = new JMenuItem(Resources.getString("dataCompare"));
    	JMenu optionsMenu = new JMenu(Resources.getString("options"));
        	JMenuItem preferencesItem = new JMenuItem(Resources.getString("preferences"));
    	JMenu helpMenu = new JMenu(Resources.getString("help"));
    		JMenuItem debugDialogItem = new JMenuItem(Resources.getString("consoleDebug"));
        	JMenuItem aboutItem = new JMenuItem(Resources.getString("about"));
    	fileMenu.addMenuListener(new
			MenuListener()
    		{
				public void menuSelected(MenuEvent e) 
				{
					JMenu menu = (JMenu) e.getSource();
					boolean isEnabled;
					OpenFileWindow patientWindow = (OpenFileWindow)tabbedPane.getSelectedComponent();
                    if(patientWindow == null)
                    	isEnabled = false;
                    else
                    	isEnabled = true;
                    menu.getItem(2).setEnabled(isEnabled);
                	menu.getItem(3).setEnabled(isEnabled);
                	menu.getItem(4).setEnabled(isEnabled);
				}
				public void menuDeselected(MenuEvent e) {}
				public void menuCanceled(MenuEvent e) {}
    		}
		);
        newItem.addActionListener(new
            ActionListener(){
                public void actionPerformed(ActionEvent event)
                {
                    OpenFileWindow openFile = getNewWindow();
                    tabbedPane.setSelectedComponent(openFile);
                    setStatusMessage(Resources.getString("ready"));
                }
            }
        );
        openItem.addActionListener(new
            ActionListener(){
                public void actionPerformed(ActionEvent event)
                {
                    JFileChooser chooser = new JFileChooser();
                    FileNameExtensionFilter filter = new FileNameExtensionFilter(
                        "Elite files", "elite");
                    chooser.setFileFilter(filter);
                    int returnVal = chooser.showOpenDialog(mainFrame);
                    if(returnVal == JFileChooser.APPROVE_OPTION)
                    {
                    	setStatusMessage(Resources.getString("opening"));
                    	File file = chooser.getSelectedFile();
                    	if(!isOpenFile(file))
                    	{
                    		OpenFileWindow openFile = getNewWindow(FileTasks.open(file),file);
                    		tabbedPane.setSelectedComponent(openFile);
                    	}
                    	else
                    		tabbedPane.setSelectedIndex(getIndexTabFile(file));
                    	setStatusMessage(Resources.getString("ready"));
                    }
                }
            }
        );
        saveItem.addActionListener(new
            ActionListener(){
                public void actionPerformed(ActionEvent event)
                {
                    OpenFileWindow patientWindow = (OpenFileWindow)tabbedPane.getSelectedComponent();
                    if(patientWindow == null)
                    	setStatusMessage(Resources.getString("noSelectedWindow"));
                    else 
                    {
                    	setStatusMessage(Resources.getString("saving"));
                        if(patientWindow.getFile() == null)
                        	saveAs(patientWindow);
                        else
                            FileTasks.save(patientWindow.getFile(),patientWindow.getPatient());
                        setStatusMessage(Resources.getString("ready"));
                    }
                }
            }
        );
        saveAsItem.addActionListener(new
            ActionListener(){
                public void actionPerformed(ActionEvent event)
                {
                    OpenFileWindow patientWindow = (OpenFileWindow)tabbedPane.getSelectedComponent();
                    if(patientWindow == null)
                    	setStatusMessage(Resources.getString("noSelectedWindow"));
                    else
                    {
                    	setStatusMessage(Resources.getString("saving"));
                    	saveAs(patientWindow);
                    	setStatusMessage(Resources.getString("ready"));
                    }
                }
            }
        );
        printItem.addActionListener(new
            ActionListener(){
                public void actionPerformed(ActionEvent event)
                {
                    OpenFileWindow patientWindow = (OpenFileWindow)tabbedPane.getSelectedComponent();
                    if(patientWindow == null)
                    	setStatusMessage(Resources.getString("noSelectedWindow"));   
                    else
                    {
                        ResultsPrint print = new ResultsPrint(mainFrame,patientWindow.getPatient(),patientWindow.getDiagnostic(),patientWindow.getFileTitle());
                        print.setLocation(getCenteringDim(mainFrame.getSize(),print.getSize()));
                        print.setVisible(true);
                    }
                    
                }
            }
        );
        exitItem.addActionListener(new
            ActionListener(){
                public void actionPerformed(ActionEvent event)
                {
                    exit();
                }
            }
        );
        checkupMenu.addMenuListener(new
    			MenuListener()
        		{
    				public void menuSelected(MenuEvent e) 
    				{
    					JMenu menu = (JMenu) e.getSource();
    					boolean isEnabled;
    					OpenFileWindow patientWindow = (OpenFileWindow)tabbedPane.getSelectedComponent();
                        if(patientWindow == null)
                        	isEnabled = false;
                        else
                        	isEnabled = true;
                        menu.getItem(0).setEnabled(isEnabled);
                    	menu.getItem(1).setEnabled(isEnabled);
                    	menu.getItem(2).setEnabled(isEnabled);
    				}
    				public void menuDeselected(MenuEvent e) {}
    				public void menuCanceled(MenuEvent e) {}
        		}
    		);
        addDateItem.addActionListener(new
            ActionListener(){
	            public void actionPerformed(ActionEvent event)
	            {
	            	OpenFileWindow patientWindow = (OpenFileWindow)tabbedPane.getSelectedComponent();
                    if(patientWindow == null)
                    	setStatusMessage(Resources.getString("noSelectedWindow"));
                    else
                    {
                    	CalendarDialog calendarD = new CalendarDialog(mainFrame);
                    	calendarD.setDaysMarked(patientWindow.getPatient().getDateList());
                    	calendarD.setLocation(getCenteringDim(mainFrame.getSize(),calendarD.getSize()));
                    	calendarD.setVisible(true);
                    	Date[] days = calendarD.getSelectedDays(); 
                    	if(calendarD.existSelectedDate())
                    	{
	                    	Patient patient = patientWindow.getPatient();
			                patient.setDate(days[0]);
			                patientWindow.update(patient);
	                    	setStatusMessage(Resources.getString("dateAdded"));
                    	}
                    }
	            }
	        }
	    );
        deleteDateItem.addActionListener(new
            ActionListener(){
	            public void actionPerformed(ActionEvent event)
	            {
	            	OpenFileWindow patientWindow = (OpenFileWindow)tabbedPane.getSelectedComponent();
	            	if(patientWindow == null)
	            		setStatusMessage(Resources.getString("noSelectedWindow"));
	            	else
	            	{
	            		CalendarDialog calendarD = new CalendarDialog(mainFrame,patientWindow.getPatient().getDate());
                    	calendarD.setDaysMarked(patientWindow.getPatient().getDateList());
                    	calendarD.setNormalSelectionMode(false);
                    	calendarD.setLocation(getCenteringDim(mainFrame.getSize(),calendarD.getSize()));
                    	calendarD.setVisible(true);
                    	Date[] days = calendarD.getSelectedDays(); 
                    	if(calendarD.existSelectedDate())
                    	{
	                    	Patient patient = patientWindow.getPatient();
			                patient.deleteDate(days[0]);
			                patientWindow.update(patient);
	                    	setStatusMessage(Resources.getString("dateDeleted"));
                    	}
	            	}
	            }
	        }
	    );
        dataCompareItem.addActionListener(new 
    		ActionListener()
        	{
				public void actionPerformed(ActionEvent e) 
				{
					OpenFileWindow patientWindow = (OpenFileWindow)tabbedPane.getSelectedComponent();
                    if(patientWindow == null)
                    	setStatusMessage(Resources.getString("noSelectedWindow"));   
                    else
                    {
                        CompareData compareData = new CompareData(mainFrame,patientWindow.getPatient());
                        compareData.setLocation(getCenteringDim(mainFrame.getSize(),compareData.getSize()));
                        compareData.setVisible(true);
                    }
				}
        	}	
        );
        preferencesItem.addActionListener(new 
    		ActionListener()
	    	{
				public void actionPerformed(ActionEvent e) 
				{
					PreferencesDialog prefDialog = new PreferencesDialog(mainFrame);
					prefDialog.setLocation(getCenteringDim(mainFrame.getSize(),prefDialog.getSize()));
					prefDialog.setVisible(true);
				}
	    	}	
	    );
        debugDialogItem.addActionListener(new 
        		ActionListener()
    	    	{
    				public void actionPerformed(ActionEvent e) 
    				{
    					DebugDialog debugDialog = new DebugDialog();
    					debugDialog.setLocation(getCenteringDim(mainFrame.getSize(),debugDialog.getSize()));
    					debugDialog.setVisible(true);
    				}
    	    	}	
    	    );
        fileMenu.add(newItem);
        fileMenu.add(openItem);
        fileMenu.add(saveItem);
        fileMenu.add(saveAsItem);
        fileMenu.add(printItem);
        fileMenu.addSeparator();
        fileMenu.add(exitItem);
        checkupMenu.add(addDateItem);
        checkupMenu.add(deleteDateItem);
        checkupMenu.add(dataCompareItem);
        optionsMenu.add(preferencesItem);
        helpMenu.add(debugDialogItem);
        helpMenu.add(aboutItem);
        menuBar.add(fileMenu);
        menuBar.add(checkupMenu);
        menuBar.add(optionsMenu);
        menuBar.add(helpMenu);
        return menuBar;
    }
    private OpenFileWindow getNewWindow()
    {
        OpenFileWindow openFile = new OpenFileWindow();
        tabbedPane.addTab(openFile.getFileTitle(),openFile);
        tabbedPane.setTabComponentAt(tabbedPane.getTabCount() - 1, getTabLabel(openFile.getFileTitle(),openFile));
        return openFile;
    }
    @SuppressWarnings("unused")
	private OpenFileWindow getNewWindow(Patient patient)
    {
        OpenFileWindow openFile = new OpenFileWindow(patient);
        tabbedPane.addTab(openFile.getFileTitle(),openFile);
        tabbedPane.setTabComponentAt(tabbedPane.getTabCount() - 1, getTabLabel(openFile.getFileTitle(),openFile));
        return openFile;
    }
    private OpenFileWindow getNewWindow(Patient patient,File file)
    {
        OpenFileWindow openFile = new OpenFileWindow(patient,file);
        tabbedPane.addTab(openFile.getFileTitle(),openFile);
        tabbedPane.setTabComponentAt(tabbedPane.getTabCount() - 1, getTabLabel(openFile.getFileTitle(),openFile));
        return openFile;
    }
    private void saveAs(OpenFileWindow patientWindow)
    {
    	Patient patient = patientWindow.getPatient();
        JFileChooser chooser = new JFileChooser();
        String stringFile = patient.getLastName()+" "+patient.getName();
        chooser.setSelectedFile(
            new File(""+stringFile+".elite"));
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
            "Elite files", "elite");
        chooser.setFileFilter(filter);
        int returnVal = chooser.showSaveDialog(mainFrame);
        if(returnVal == JFileChooser.APPROVE_OPTION)
        {
            File file = chooser.getSelectedFile();
            if(file.exists())
            {
                int selection = JOptionPane.showConfirmDialog(
                    mainFrame,
                    Resources.getString(
                        "saveTitle")+
                        " ''"+stringFile+
                        "''. "+Resources.getString("saveQuestion"
                    ), 
                    Resources.getString("exit"),
                    JOptionPane. YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE);
                if (selection == JOptionPane.NO_OPTION)
                    return;
            }
            FileTasks.save(file,patient);
            patientWindow.setFile(file);
        }
    }
    private void StartLookAndFeell()
    {
        try {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } 
        catch (UnsupportedLookAndFeelException e) {
            // handle exception
        }   
        catch (ClassNotFoundException e) {
            // handle exception
        }
        catch (InstantiationException e) {
            // handle exception
        }
        catch (IllegalAccessException e) {
            // handle exception
        }
    }
    private JPanel getTabLabel(String textLabel,final OpenFileWindow openFile)
    {
    	JPanel panel = new JPanel(new GridBagLayout());
    	panel.setOpaque(false);
    	JLabel label = Components.getLabel(textLabel,Resources.FONT_TYPE.TAB_LABEL);
    	label.setOpaque(false);
    	JButton closeButton = new JButton(Resources.getImage("close_tab.png"));
    	closeButton.setHorizontalAlignment(SwingConstants.RIGHT);
    	closeButton.setHorizontalTextPosition(SwingConstants.LEFT); 
    	closeButton.setContentAreaFilled(false);
    	closeButton.setFocusable(false);
    	closeButton.setBorderPainted(false);
    	closeButton.setOpaque(false);
    	closeButton.addActionListener(new 
    			ActionListener()
    			{
    				public void actionPerformed(ActionEvent event)
    				{
    					int selection = JOptionPane.showConfirmDialog(
				            mainFrame,
				            "¿"+Resources.getString("close")+" "+openFile.getFileTitle()+"?", 
				            Resources.getString("closeTab"),
				            JOptionPane.YES_NO_OPTION,
				            JOptionPane.QUESTION_MESSAGE);
				        if (selection == JOptionPane.YES_OPTION)
				        {
				        	if(openFile.existNewInfo() || !openFile.getSavedState())
				        	{
					        	selection = JOptionPane.showConfirmDialog(
							            mainFrame,
							            Resources.getString("saveQuestion2"), 
							            Resources.getString("save"),
							            JOptionPane.YES_NO_OPTION,
							            JOptionPane.QUESTION_MESSAGE);
					        	if (selection == JOptionPane.YES_OPTION)
					        	{
					        		openFile.confirmNewValues();
					        		if(openFile.getFile() == null)
					        			saveAs(openFile);
					        		else
					        			FileTasks.save(openFile.getFile(),openFile.getPatient());
					        	}
				        	}
			        		tabbedPane.remove(openFile);
				        }
    				}
    			});
    	panel.add(label,new GridBagConstraints( 
    			0, 
    			0, 
    			1,
    			1,
    			0,
    			0,
    			GridBagConstraints.CENTER,
    			GridBagConstraints.HORIZONTAL,
    			new Insets(0,0,0,0),
    			0,
    			0));
    	panel.add(closeButton,new GridBagConstraints(
    			1, 
    			0, 
    			1,
    			1,
    			0,
    			0,
    			GridBagConstraints.EAST,
    			GridBagConstraints.NONE,
    			new Insets(-3,-3,-3,-6),
    			0,
    			0));
    	return panel;
    }
    private void exit()
    {
    	int selection = JOptionPane.showConfirmDialog(
            mainFrame,
            Resources.getString("exitDialog"), 
            Resources.getString("exit"),
            JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.WARNING_MESSAGE);
        if (selection == JOptionPane.OK_OPTION)
            System.exit(0);
    }
    private boolean isOpenFile(File file)
    {
    	for(int i = 0; i < tabbedPane.getTabCount(); i++)
    	{
    		OpenFileWindow component = (OpenFileWindow) tabbedPane.getComponentAt(i);
    		if(component.getFile() != null)
    			if(component.getFile().compareTo(file) == 0)
    				return true;
    	}
    	return false;
    }
    private int getIndexTabFile(File file)
    {
    	for(int i = 0; i < tabbedPane.getTabCount(); i++)
    	{
    		OpenFileWindow component = (OpenFileWindow) tabbedPane.getComponentAt(i);
    		if(component.getFile() != null)
    			if(component.getFile().compareTo(file) == 0)
    				return i;
    	}
    	return -1;
    }    
    private Point getCenteringDim(Dimension dimFather,Dimension dimSon)
    {
    	int heightC = (int)( (dimFather.getHeight() - dimSon.getHeight())/ 2);
    	int widthC = (int)( (dimFather.getWidth() - dimSon.getWidth())/ 2);
    	Point positionFrame = mainFrame.getLocationOnScreen();
    	return new Point( positionFrame.x + widthC, positionFrame.y + heightC);
    }
    public static Point getCenteringDim(Dimension dimSon)
    {
    	int heightC = (int)( (mainFrame.getSize().getHeight() - dimSon.getHeight())/ 2);
    	int widthC = (int)( (mainFrame.getSize().getWidth() - dimSon.getWidth())/ 2);
    	Point positionFrame = mainFrame.getLocationOnScreen();
    	return new Point( positionFrame.x + widthC, positionFrame.y + heightC);
    }
    public static Point getCenteringDim(Component fatherFrame,Dimension dimSon)
    {
    	int heightC = (int)( (fatherFrame.getSize().getHeight() - dimSon.getHeight())/ 2);
    	int widthC = (int)( (fatherFrame.getSize().getWidth() - dimSon.getWidth())/ 2);
    	Point positionFrame = fatherFrame.getLocationOnScreen();
    	return new Point( positionFrame.x + widthC, positionFrame.y + heightC);
    }
    public static void setStatusMessage(String message)
    {
    	statusBar.setMessage(message);
    }
    private static class StatusBar extends JLabel
    {
    	public StatusBar(Font font)
    	{
    		super();
    		this.setFont(font);
    		this.setText(Resources.getString("ready"));
    	}
    	public void setMessage(String message)
    	{
    		this.setText(message);
    	}
    }
    public static JFrame getMainFrame()
    {
    	return mainFrame;
    }
    private class DebugDialog extends JDialog
    {
    	public DebugDialog()
    	{
    		super(mainFrame,"Debug",false);
    		JPanel panel = new JPanel(new BorderLayout());
    		consoleDebug.setEditable(false);
    		panel.add(new JScrollPane(consoleDebug), BorderLayout.CENTER);
    		this.add(panel);
    		this.setSize(600,200);
    	}
    }
    public static void addTextDebug(String text)
    {
    	consoleDebug.insert(text+'\n', consoleDebug.getText().length());
    }
    static
    {
    	statusBar = new StatusBar(Resources.getFont(Resources.FONT_TYPE.STATUS_BAR));
    	mainFrame = new JFrame();
    	consoleDebug = new JTextArea();
    }
    private static JTextArea consoleDebug;
    private static StatusBar statusBar;
    private static JFrame mainFrame;
    private JTabbedPane tabbedPane;
    private static final int HEIGHT = 600;
    private static final int WIDTH  = 1024;
}
